var express = require('express');
var router = express.Router();
// 导入模型对象
const {
    Cate,
    Article
} = require('../models')
const moment = require('moment')

// 首页导航栏的分类数据
router.get('/index/cate', async function(req, res, next) {
    // 根据从大到小的顺序来排序
    const result = await Cate.findAll({
        attributes: ['id', 'cate_name'],
        order: [
            ['sort', 'desc']
        ]
    })
    if (result.length) {
        return res.cc(200, {
            code: 200,
            msg: '查询成功',
            data: result
        })
    } else {
        return res.cc(400, {
            code: 400,
            msg: '查询失败'
        })
    }
});

// 首页的图片新闻
router.get('/index/pic', async(req, res) => {
    // 根据访问量最小的5个
    const page = req.query.page - 0 || 1
    const limit = req.query.limit - 0 || 5
    const result = await Article.findAll({
        attributes: ['id', 'title', 'picture'],
        order: [
            ['view_nums', 'asc']
        ],
        limit,
        offset: (page - 1) * limit
    })
    if (result.length) {
        return res.cc(200, {
            code: 200,
            msg: '查询成功',
            data: result
        })
    } else {
        return res.cc(400, {
            code: 400,
            msg: '查询失败'
        })
    }
})

// 首页的最新新闻
router.get('/index/new', async(req, res) => {
    const page = req.query.page - 0 || 1
    const limit = req.query.limit - 0 || 10
    const result = await Article.findAll({
        attributes: ['id', 'title', 'add_time'],
        order: [
            ['add_time', 'desc']
        ],
        limit,
        offset: (page - 1) * limit
    })
    if (result.length) {
        result.forEach(item => {
            item.dataValues.add_time = moment(item.dataValues.add_time).format('YYYY-MM-DD HH:mm:ss')
        })
        return res.cc(200, {
            code: 200,
            msg: '查询成功',
            data: result
        })
    } else {
        return res.cc(400, {
            code: 400,
            msg: '查询失败'
        })
    }
})

// 首页的最热新闻
router.get('/index/hot', async(req, res) => {
    const page = req.query.page - 0 || 1
    const limit = req.query.limit - 0 || 10
    const result = await Article.findAll({
        attributes: ['id', 'title', 'add_time'],
        order: [
            ['view_nums', 'desc']
        ],
        limit,
        offset: (page - 1) * limit
    })
    if (result.length) {
        result.forEach(item => {
            item.dataValues.add_time = moment(item.dataValues.add_time).format('YYYY-MM-DD HH:mm:ss')
        })
        return res.cc(200, {
            code: 200,
            msg: '查询成功',
            data: result
        })
    } else {
        return res.cc(400, {
            code: 400,
            msg: '查询失败'
        })
    }
})


module.exports = router;